<template>
  <div class="hot-ranking-container">
    <a-card class="hot-ranking-card" :bordered="false">
      <template #title>
        <div class="page-header">
          <div class="title-section">
            <span class="emoji-title">🔥</span>
            <span class="main-title">热门榜单</span>
            <span class="emoji-title">📊</span>
          </div>
          <div class="subtitle" v-if="rankingData">{{ rankingData.subtitle }}</div>
        </div>
      </template>

      <!-- 平台选择 (多列单选按钮) -->
      <div class="platform-selector">
        <a-radio-group
          v-model:value="selectedPlatform"
          button-style="solid"
          @change="fetchRankingData"
          class="platform-radio-group"
        >
          <div class="platform-grid">
            <a-radio-button v-for="platform in platforms" :key="platform.value" :value="platform.value" class="platform-button">
              <span class="platform-icon">{{ platform.icon }}</span>
              <span class="platform-name">{{ platform.label }}</span>
            </a-radio-button>
          </div>
        </a-radio-group>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <a-spin tip="正在获取热榜数据...">
          <div class="loading-content">
            <a-skeleton active :paragraph="{ rows: 10 }" />
          </div>
        </a-spin>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error-container">
        <a-result
          status="error"
          title="获取热榜数据失败"
          :sub-title="error"
        >
          <template #extra>
            <a-button type="primary" @click="fetchRankingData">
              重试
            </a-button>
          </template>
        </a-result>
      </div>

      <!-- 热榜数据展示 -->
      <div v-else-if="rankingData && rankingData.data" class="ranking-content">
        <!-- 热榜信息 -->
        <div class="ranking-info">
          <div class="info-item">
            <clock-circle-outlined />
            <span>更新时间: {{ formatTime(rankingData.updateTime) }}</span>
          </div>
          <div class="info-item">
            <unordered-list-outlined />
            <span>总条数: {{ rankingData.total }}</span>
          </div>
          <div class="info-item">
            <cloud-server-outlined />
            <span>数据来源: {{ rankingData.from }}</span>
          </div>
        </div>

        <!-- 视图切换 -->
        <div class="view-toggle">
          <a-radio-group v-model:value="viewMode" button-style="solid">
            <a-radio-button value="compact">
              <ordered-list-outlined />
              紧凑视图
            </a-radio-button>
            <a-radio-button value="list">
              <bars-outlined />
              列表视图
            </a-radio-button>

          </a-radio-group>
        </div>

        <!-- 列表视图 -->
        <div v-if="viewMode === 'list'" class="list-view">
          <a-list
            :dataSource="rankingData.data"
            :pagination="{ pageSize: 10, showSizeChanger: true, pageSizeOptions: ['10', '20', '50', '100'] }"
          >
            <template #renderItem="{ item, index }">
              <a-list-item>
                <a-list-item-meta>
                  <template #avatar>
                    <div class="list-rank" :class="{'top-rank': index < 3}">{{ index + 1 }}</div>
                  </template>
                  <template #title>
                    <div class="list-title">
                      <span class="title-text">{{ item.title }}</span>
                      <div class="list-stats">
                        <div class="stat-item" v-if="item.data && item.data.view">
                          <eye-outlined />
                          <span>{{ formatNumber(item.data.view) }}</span>
                        </div>
                        <div class="stat-item" v-if="item.hot">
                          <fire-outlined />
                          <span>{{ formatNumber(item.hot) }}</span>
                        </div>
                      </div>
                    </div>
                  </template>
                  <template #description>
                    <div class="list-desc">
                      <div v-if="item.desc">{{ item.desc }}</div>
                      <div class="list-owner" v-if="item.owner">
                        <a-avatar :src="item.owner.face" :size="20" />
                        <span>{{ item.owner.name }}</span>
                      </div>
                    </div>
                  </template>
                </a-list-item-meta>
                <template #actions>
                  <a-button
                    type="link"
                    size="small"
                    @click="openLink(item)"
                  >
                    <template #icon><link-outlined /></template>
                    查看
                  </a-button>
                </template>
                <template #extra v-if="hasPicture(item)">
                  <img :src="item.pic" :alt="item.title" class="list-image" />
                </template>
              </a-list-item>
            </template>
          </a-list>
        </div>

        <!-- 紧凑视图 -->
        <div v-else-if="viewMode === 'compact'" class="compact-view">
          <a-list
            :dataSource="rankingData.data"
            size="small"
            :pagination="{ pageSize: 20, showSizeChanger: true, pageSizeOptions: ['20', '50', '100'] }"
          >
            <template #renderItem="{ item, index }">
              <a-list-item class="compact-item" @click="openLink(item)">
                <div class="compact-rank" :class="{'top-rank': index < 3}">{{ index + 1 }}</div>
                <div class="compact-content">
                  <div class="compact-title">{{ item.title }}</div>
                  <div class="compact-stats">
                    <div class="stat-item" v-if="item.hot">
                      <fire-outlined />
                      <span>{{ formatNumber(item.hot) }}</span>
                    </div>
                    <div class="compact-owner" v-if="item.owner">
                      <user-outlined />
                      <span>{{ item.owner.name }}</span>
                    </div>
                  </div>
                </div>
              </a-list-item>
            </template>
          </a-list>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-container">
        <a-empty description="暂无热榜数据">
          <template #description>
            <span>请选择平台获取热榜数据</span>
          </template>
        </a-empty>
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import axios from 'axios';
import {
  ClockCircleOutlined,
  UnorderedListOutlined,
  CloudServerOutlined,
  BarsOutlined,
  OrderedListOutlined,
  EyeOutlined,
  LikeOutlined,
  FireOutlined,
  LinkOutlined,
  UserOutlined
} from '@ant-design/icons-vue';

// 状态定义
const loading = ref(false);
const error = ref(null);
const rankingData = ref(null);
const selectedPlatform = ref('哔哩哔哩');
const viewMode = ref('list'); // 默认使用列表视图

// 平台列表
const platforms = [
  { label: '哔哩哔哩', value: '哔哩哔哩', icon: '📺' },
  { label: '百度', value: '百度', icon: '🔍' },
  { label: '知乎', value: '知乎', icon: '❓' },
  { label: '百度贴吧', value: '百度贴吧', icon: '💬' },
  { label: '少数派', value: '少数派', icon: '📱' },
  { label: 'IT之家', value: 'IT之家', icon: '💻' },
  { label: '澎湃新闻', value: '澎湃新闻', icon: '📰' },
  { label: '今日头条', value: '今日头条', icon: '📺' },
  { label: '微博热搜', value: '微博热搜', icon: '🔥' },
  { label: '36氪', value: '36氪', icon: '💼' },
  { label: '稀土掘金', value: '稀土掘金', icon: '🔨' },
  { label: '腾讯新闻', value: '腾讯新闻', icon: '📱' }
];

// 获取热榜数据
const fetchRankingData = async () => {
  loading.value = true;
  error.value = null;

  try {
    const response = await axios.get('https://api.pearktrue.cn/api/dailyhot/', {
      params: {
        title: selectedPlatform.value
      },
      timeout: 10000
    });

    console.log('API响应:', response);

    if (response.data && response.data.code === 200) {
      rankingData.value = response.data;
      message.success(`成功获取 ${selectedPlatform.value} 热榜数据`);
    } else {
      error.value = response.data?.message || '获取热榜数据失败';
      message.error(error.value);
    }
  } catch (err) {
    console.error('获取热榜数据失败:', err);
    error.value = `网络错误: ${err.message}`;
    message.error(error.value);
  } finally {
    loading.value = false;
  }
};

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return '';

  const date = new Date(timeString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 格式化数字（添加千位分隔符）
const formatNumber = (num) => {
  if (!num && num !== 0) return '';

  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万';
  }

  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 检查是否有图片
const hasPicture = (item) => {
  return item && item.pic && item.pic.trim() !== '';
};

// 打开链接
const openLink = (item) => {
  let url = '';

  if (item.mobileUrl) {
    url = item.mobileUrl;
  } else if (item.url) {
    url = item.url;
  } else if (selectedPlatform.value === '哔哩哔哩' && item.id) {
    url = `https://www.bilibili.com/video/${item.id}`;
  } else if (selectedPlatform.value === '知乎' && item.id) {
    url = `https://www.zhihu.com/question/${item.id}`;
  } else {
    message.info('无法获取详情链接');
    return;
  }

  window.open(url, '_blank');
};

// 页面加载时获取默认平台的热榜数据
onMounted(() => {
  fetchRankingData();
});
</script>

<style scoped>
.hot-ranking-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.hot-ranking-card {
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  background: linear-gradient(to bottom, #ffffff, #f9f9f9);
}

.page-header {
  text-align: center;
  margin-bottom: 16px;
}

.title-section {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.emoji-title {
  font-size: 2rem;
}

.main-title {
  font-size: 2rem;
  font-weight: bold;
  background: linear-gradient(45deg, #ff4d4f, #ff7a45);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.subtitle {
  font-size: 1rem;
  color: #666;
  margin-top: 8px;
}

/* 平台选择 */
.platform-selector {
  margin-bottom: 24px;
  overflow-x: hidden;
}

.platform-radio-group {
  width: 100%;
}

.platform-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 10px;
  width: 100%;
}

.platform-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  height: 36px;
  width: 100%;
}

.platform-icon {
  font-size: 1.1rem;
}

.platform-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 加载状态 */
.loading-container, .error-container, .empty-container {
  padding: 60px 0;
  text-align: center;
}

.loading-content {
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
}

/* 热榜内容区域 */
.ranking-content {
  animation: fadeIn 0.5s ease-in-out;
}

.ranking-info {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
}

/* 视图切换 */
.view-toggle {
  display: flex;
  justify-content: center;
  margin-bottom: 24px;
}

/* 列表视图 */
.list-view {
  margin-bottom: 24px;
}

.list-rank {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  color: #666;
  border-radius: 50%;
  font-weight: bold;
}

.list-rank.top-rank {
  background-color: #ff4d4f;
  color: white;
}

.list-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.list-stats {
  display: flex;
  gap: 16px;
  flex-shrink: 0;
}

.list-desc {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.list-owner {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 0.9rem;
  color: #666;
}

.list-image {
  width: 120px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

/* 紧凑视图 */
.compact-view {
  margin-bottom: 24px;
}

.compact-item {
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 16px;
  transition: background-color 0.3s;
}

.compact-item:hover {
  background-color: #f5f5f5;
}

.compact-rank {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f0f0;
  color: #666;
  border-radius: 50%;
  font-weight: bold;
  flex-shrink: 0;
}

.compact-rank.top-rank {
  background-color: #ff4d4f;
  color: white;
}

.compact-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.compact-title {
  font-weight: 500;
}

.compact-stats {
  display: flex;
  gap: 16px;
  color: #666;
  font-size: 0.9rem;
}

.compact-owner {
  display: flex;
  align-items: center;
  gap: 4px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #666;
  font-size: 0.9rem;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

@media (max-width: 768px) {
  .hot-ranking-container {
    padding: 10px;
  }

  .main-title {
    font-size: 1.5rem;
  }

  .emoji-title {
    font-size: 1.5rem;
  }

  .platform-grid {
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 8px;
  }

  .platform-button {
    height: 32px;
    padding: 0 8px;
  }

  .platform-name {
    font-size: 0.9rem;
  }

  .list-title {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .list-image {
    width: 80px;
    height: 60px;
  }
}

@media (max-width: 480px) {
  .platform-grid {
    grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
    gap: 6px;
  }

  .platform-name {
    font-size: 0.8rem;
  }

  .platform-icon {
    font-size: 1rem;
  }
}
</style>
